package com.czq.service.serviceImpl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czq.common.BaseContext;
import com.czq.dao.OrdersDao;
import com.czq.pojo.*;
import com.czq.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
   @Autowired
   private UserService userService;
   @Autowired
   private AddressBookService addressBookService;
   @Autowired
   private ShoppingCartService shoppingCartService;
   @Autowired
   private OrderDetailService orderDetailService;

    @Override
    @Transactional
    public void submit(Orders orders) {
        Long userid = BaseContext.getCurrentId();//获取userid。
        LambdaQueryWrapper<User> queryWrapperUser = new LambdaQueryWrapper<>();
//        根据userid查询user表，获取name
        queryWrapperUser.eq(User::getId,userid);
        User user = userService.getOne(queryWrapperUser);
        String name = user.getName();      //获得user的name，要添加到order的user_name;
        
//        存入user_name和user_id到order表里面
        orders.setUserName(name);
        orders.setUserId(userid);


//        查询地址表，然后获取地址表里的下单用户（consignee）和phone和detail（地址）
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<AddressBook>();
        queryWrapper.eq(AddressBook::getId,orders.getAddressBookId());
        AddressBook address = addressBookService.getOne(queryWrapper);
        String consignee = address.getConsignee();
        String phone = address.getPhone();
        String detail = address.getDetail();
        long id = IdWorker.getId();
        AtomicInteger amount = new AtomicInteger(0);

        //查询购物车表
        LambdaQueryWrapper<ShoppingCart> s=new LambdaQueryWrapper<ShoppingCart>();
        s.eq(ShoppingCart::getUserId,userid);
        List<ShoppingCart> list = shoppingCartService.list(s);
        List<OrderDetail> details=new ArrayList<OrderDetail>();
        for (ShoppingCart cart : list){
            String shoppName = cart.getName();//获取购物车的菜名
            String image = cart.getImage();//获取图片
            Long dishId = cart.getDishId();
            Long setmealId = cart.getSetmealId();
            String dishFlavor = cart.getDishFlavor();
            Integer shoppingnumber = cart.getNumber();
            BigDecimal shoppingAmount = cart.getAmount();

            //给订单明细表的对象赋值
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppName);
            orderDetail.setImage(image);
            orderDetail.setOrderId(id);
            orderDetail.setDishId(dishId);
            orderDetail.setSetmealId(setmealId);
            orderDetail.setDishFlavor(dishFlavor);
            orderDetail.setNumber(shoppingnumber);
            orderDetail.setAmount(shoppingAmount);
            details.add(orderDetail);
            amount.addAndGet(shoppingAmount.multiply(new BigDecimal(shoppingnumber)).intValue());



        }


        //把根据在地址表里查询的下单用户name，地址，phone存入order中
        orders.setConsignee(consignee);
        orders.setPhone(phone);
        orders.setAddress(detail);
        orders.setStatus(1);//1,待支付
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setOrderTime(LocalDateTime.now());
//        设置总钱
        orders.setAmount(new BigDecimal(amount.get()));

        orders.setId(id);
        String number = String.valueOf(id);
        orders.setNumber(number);//设置订单号
        this.save(orders);
        orderDetailService.saveBatch(details);

        shoppingCartService.remove(s);

//        Random random=new Random();
//        int pay_method = random.nextInt(2) + 1; //随机生成1或者2；
//        orders.setPayMethod(pay_method);//设置1微信支付，2支付宝支付



    }

    @Override
    public List<OrdersDto>  selectall() {

        Long useId = BaseContext.getCurrentId();

        LambdaQueryWrapper<Orders> orderQuery=new LambdaQueryWrapper<Orders>();
        LambdaQueryWrapper<OrderDetail> orderDetailQuery=new LambdaQueryWrapper<OrderDetail>();

        orderQuery.eq(Orders::getUserId,useId);
        List<Orders> list = this.list(orderQuery);//查询全部Orders表的信息。
        List<Long> orderIds = new ArrayList<Long>();
        List<OrdersDto> ordersDtos=new ArrayList<OrdersDto>();
        for (Orders order : list) {
            orderIds.add(order.getId());//获得每个order表里的id，这个id用来查询OrderDetail的数据

        }
//        if (orderIds.size()==0){
//            return null;
//        }
//        else {
            List<OrderDetail> orderDetail = orderDetailService.list(orderDetailQuery);

            for (Orders o :list){
                OrdersDto ordersDto = new OrdersDto();
                BeanUtils.copyProperties(o,ordersDto);   //拷贝orders对象的数据
                ordersDto.setOrderDetails(orderDetail);
                ordersDtos.add(ordersDto);   //放到 List<OrdersDto> ordersDtos里面
            }
//        }
//        orderDetailQuery.in(OrderDetail::getOrderId,orderIds);

//        select * from orderDetail where  orderid in(1,2,3);

        return ordersDtos;




    }
}
